-- Maquina de estado

library ieee;
use ieee.std_logic_1164.all;

entity MDE is
	port(
		SET : in std_logic; -- Button de set para mudar de estado, ativo baixo
		RESET : in std_logic; -- Reset
		CLK : in std_logic; -- Clock 50MHz
		AT : in std_logic; -- Acabou o tempo, vem do temporizador
		COUNT : out std_logic; -- Sinal para contar para o temporizador
		DEMUX : out std_logic_vector(1 downto 0) -- Enable para o demux
	);
end MDE;

architecture DT_FLOW of MDE is
type STATE_TYPE is (INI, HOR, MIN, SEG);
signal STATE : STATE_TYPE;
signal NEXT_STATE : STATE_TYPE;

begin

	process(CLK, RESET, SET, AT)
	begin
	
	if (RESET = '0') then
			STATE <= INI;
	elsif (CLK'EVENT AND CLK = '1') then
		case STATE is
			when INI =>
				if (SET = '0') then
					STATE <= NEXT_STATE;
				else
					STATE <= INI;
				end if;
			when HOR =>
				if (SET = '0') then
					STATE <= NEXT_STATE;
				elsif (AT = '1') then
					STATE <= INI;
				end if;
			when MIN =>
				if (SET = '0') then
					STATE <= NEXT_STATE;
				elsif (AT = '1') then
					STATE <= INI;
				end if;
			when SEG =>
				if (SET = '0') then
					STATE <= NEXT_STATE;
				elsif (AT = '1') then
					STATE <= INI;
				end if;
		end case;
	end if;
	
	end process;
	
	
	process(STATE)
	begin
	
	case STATE is
		when INI => 
					NEXT_STATE <= HOR;
					COUNT <= '0';
					DEMUX <= "00";
		when HOR => 
					NEXT_STATE <= MIN;
					COUNT <= '1';
					DEMUX <= "01";
		when MIN => 
					NEXT_STATE <= SEG;
					COUNT <= '1';
					DEMUX <= "10";
		when SEG => 
					NEXT_STATE <= INI;
					COUNT <= '1';
					DEMUX <= "11";
	end case;
	end process;

end DT_fLOW;

